<?php

use Mapper\SparringsellModel as SprSellMapper;
use Mapper\MemberModel as MemberMapper;
use Mapper\SparringgameModel as GameMapper;

class SparringsellController extends \Base\ApiController {

    /**
     * @desc 求大腿列表
     */
    public function publishListAction() {
        $request = $this->getRequest();
        $page    = (int)$request->get('page', 1);
        $perPage = (int)$request->get('per_page', 15);
        $page    = max(1, $page);
        $perPage = min(30, $perPage);
        $limit   = $perPage;
        $offset  = $limit * ($page - 1);

        $sprSellMapper = SprSellMapper::getInstance();
        $models        = $sprSellMapper->fetchAll([
            'status'       => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
            'end_time > ?' => time(),
        ], 'add_time DESC', $limit, $offset);

        if(empty($models)) {
            return \Response::data([]);
        }

        $memberMapper = MemberMapper::getInstance();
        $gameMapper   = GameMapper::getInstance();
        $return       = [];

        // 添加昵称,时间段数据
        foreach($models as $model) {
            $memberModel = $memberMapper->findById($model->getUid());

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('Invalid uid', 10110);
            }

            $sellArr                  = $model->toArray();
            $sellArr['nickname']      = urldecode($memberModel->getNick_name());
            $sellArr['time_interval'] = date('m月d日 H:s', $model->getBegin_time()) . ' - ' .
                date('m月d日 H:s', $model->getEnd_time());

            $gameModel = $gameMapper->findById($model->getGame_id());

            if(!$memberModel instanceof \MemberModel) {
                $arr['nickname'] = '';
                $arr['avatar']   = '';
            } else {
                $arr['nickname'] = urldecode($memberModel->getNick_name());
                $arr['avatar']   = $memberModel->getAvatar();
            }

            if(!$gameModel instanceof \SparringGameModel) {
                $arr['game_name'] = '';
            } else {
                $arr['game_name'] = $gameModel->getGame_name();
            }

            $return[] = $sellArr;
        }

        return \Response::data($return);
    }

    /**
     * @desc   求大腿发布接口
     *
     * @return false
     */
    public function publishAction() {
        $request    = $this->getRequest();
        $uid        = \Lib\User::getInstance()->id();
        $gameId     = (int)$request->get('game_id');
        $netBar     = (string)$request->get('net_bar');
        $price      = (float)$request->get('price', 0.00);
        $beginTime  = (string)$request->get('begin_time');
        $endTime    = (string)$request->get('end_time');
        $gameLevel  = (string)$request->get('game_level');
        $gameServer = (string)$request->get('game_server');
        $manifesto  = (string)$request->get('manifesto');

        if($gameId <= 0) {
            return \Response::error('游戏名不能为空', 10201);
        }

        if($price <= 0) {
            return \Response::error('价格数字有误', 10202);
        }

        $beginTime = strtotime($beginTime);

        if(empty($beginTime)) {
            return \Response::error('空闲的开始时间不能为空', 10203);
        }

        $endTime = strtotime($endTime);

        if(empty($endTime)) {
            return \Response::error('空闲的结束时间不能为空', 10204);
        }

        $model = new \SparringSellModel();
        $model->setUid($uid);
        $model->setGame_id($gameId);
        $model->setNet_bar($netBar);
        $model->setPrice($price);
        $model->setBegin_time($beginTime);
        $model->setEnd_time($endTime);
        $model->setGame_level($gameLevel);
        $model->setGame_server($gameServer);
        $model->setManifesto($manifesto);
        $model->setStatus(\Lib\Consts::SPARRING_SELL_STATUS_NORMAL);
        $model->setAdd_time(time());

        $sprSellMapper = SprSellMapper::getInstance();

        try {
            $id = $sprSellMapper->insert($model);
            return $id > 0 ? \Response::data(null) : \Response::error('求大腿发布失败', 10224);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 编辑求大腿发布信息
     *
     * @return false
     */
    public function publishEditAction() {
        $request    = $this->getRequest();
        $uid        = \Lib\User::getInstance()->id();
        $sellId     = (int)$request->get('sell_id', 0);
        $gameId     = (int)$request->get('game_id');
        $netBar     = (string)$request->get('net_bar');
        $price      = (float)$request->get('price', 0.00);
        $gameLevel  = (string)$request->get('game_level');
        $gameServer = (string)$request->get('game_server');
        $manifesto  = (string)$request->get('manifesto');

        if($sellId <= 0) {
            return \Response::error('求大腿id值不能为空', 10221);
        }

        $sprSellMapper = SprSellMapper::getInstance();
        $model         = $sprSellMapper->fetch(['uid' => $uid, 'id' => $sellId]);

        if(!$model instanceof \SparringSellModel) {
            return \Response::error('Invalid SellId', 10209);
        }

        if(empty($gameName)) {
            return \Response::error('游戏名不能为空', 10201);
        }

        if($price <= 0) {
            return \Response::error('价格数字有误', 10202);
        }

        $model->setGame_id($gameId);
        $model->setNet_bar($netBar);
        $model->setPrice($price);
        $model->setGame_level($gameLevel);
        $model->setGame_server($gameServer);
        $model->setManifesto($manifesto);
        $model->setUpdate_time(time());

        try {
            $rows = $sprSellMapper->update($model, ['id' => $sellId]);
            return $rows > 0 ? \Response::data(null) : \Response::error('求大腿发布信息更新失败', 10225);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 求大腿发布的信息详情
     *
     * @return false
     */
    public function publishDetailAction() {
        $request = $this->getRequest();
        $sellId  = $request->get('sell_id', 0);

        if(empty($sellId)) {
            return \Response::error('id值不能为空', 10208);
        }

        $sprSellMapper = sprSellMapper::getInstance();
        $model         = $sprSellMapper->findById($sellId);

        if(!$model instanceof \SparringSellModel) {
            return \Response::error('Invalid SellId', 10209);
        }

        $data                  = $model->toArray();
        $data['time_interval'] = date('m月d日 H:s', $model->getBegin_time()) . ' - ' .
            date('m月d日 H:s', $model->getEnd_time());

        $uid          = $model->getUid();
        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('Invalid Uid', 10229);
        }

        $data['uid']      = $uid;
        $data['avatar']   = $memberModel->getAvatar();
        $data['nickname'] = urldecode($memberModel->getNick_name());

        $gameMapper = GameMapper::getInstance();
        $gameModel  = $gameMapper->findById($model->getGame_id());

        if(!$gameModel instanceof \SparringGameModel) {
            $data['game_name'] = '';
        } else {
            $data['game_name'] = $gameModel->getGame_name();
        }

        return \Response::data($data, '获得发布详情成功');
    }

    /**
     * @desc 求大腿搜索功能
     *
     * @return false
     */
    public function searchAction() {
        $request = $this->getRequest();
        $search  = $request->get('search', '');
        $type    = (string)$request->get('type', 'nickname');
        $page    = (int)$request->get('page', 1);
        $perPage = (int)$request->get('per_page', 15);
        $page    = max(1, $page);
        $perPage = min(30, $perPage);
        $limit   = $perPage;
        $offset  = $limit * ($page - 1);

        if(empty($search)) {
            return \Response::error('搜索文字不能为空', 10206);
        }

        $memberMapper = MemberMapper::getInstance();

        if($type === 'nickname') {
            $search      = urlencode($search);
            $memberModel = $memberMapper->findByNick_name($search);

            if(!$memberModel instanceof \MemberModel) {
                return \Response::data([], '昵称搜索结果为空');
            }

            $uid = $memberModel->getId();
        } elseif($type === 'uid') {
            $uidStr = strlen($search);

            if((int)$search < 65535 || $uidStr < 5 || $uidStr > 10) {
                return \Response::data([], 'Uid搜索结果为空');
            }

            $memberModel = $memberMapper->findById($search);

            if(!$memberModel instanceof \MemberModel) {
                return \Response::data([], 'Uid搜索结果为空');
            }

            $uid = $search;
        } else {
            return \Response::error('搜索类型有误', 10222);
        }

        $sprSellMapper = sprSellMapper::getInstance();
        // 通过uid搜索
        $sprSellModels = $sprSellMapper->fetchAll([
            'uid'          => $uid,
            'status'       => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
            'end_time > ?' => time(),
        ], 'add_time DESC', $limit, $offset);

        if(empty($sprSellModels)) {
            return \Response::data([], '搜索结果为空');
        }

        $return = [];

        foreach($sprSellModels as $sprSellModel) {
            $value                  = $sprSellModel->toArray();
            $value['nickname']      = urldecode($memberModel->getNick_name());
            $value['time_interval'] = date('m月d日 H:s', $sprSellModel->getBegin_time()) . ' - ' .
                date('m月d日 H:s', $sprSellModel->getEnd_time());
            $return[]               = $value;
        }

        return \Response::data($return, '搜索成功');
    }

    /**
     * @desc 我的发布-求大腿列表
     */
    public function myPublishListAction() {
        $request = $this->getRequest();
        $uid     = \Lib\User::getInstance()->id();
        $page    = (int)$request->get('page', 1);
        $perPage = (int)$request->get('per_page', 10);
        $page    = max(1, $page);
        $perPage = min(30, $perPage);
        $limit   = $perPage;
        $offset  = $limit * ($page - 1);

        $sprSellMapper = SprSellMapper::getInstance();
        $gameMapper    = GameMapper::getInstance();
        $models        = $sprSellMapper->fetchAll([
            'status' => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
            'uid'    => $uid,
        ], 'add_time DESC', $limit, $offset);
        $return        = [];

        if(!empty($models)) {
            foreach($models as $sellModel) {
                $data                  = $sellModel->toArray();
                $data['time_interval'] = date('m月d日 H:s', $sellModel->getBegin_time()) . ' - ' .
                    date('m月d日 H:s', $sellModel->getEnd_time());

                $gameModel = $gameMapper->findById($sellModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $tmp['date']   = date('m月d日', $sellModel->getAdd_time());
                $tmp['data'][] = $data;

                if(isset($return['data'][$sellModel->getAdd_time()])) {
                    $return[$sellModel->getAdd_time()]['data'][] = $data;
                } else {
                    $return[$sellModel->getAdd_time()] = $tmp;
                }

                unset($tmp);
            }
        }

        if(!empty($return)) {
            $return = array_values($return);
        }


        return \Response::data($return);
    }

    /**
     * @desc  我的发布-求大腿信息删除
     * @return false
     */
    public function myPublishDelAction() {
        $request = $this->getRequest();
        $uid     = \Lib\User::getInstance()->id();
        $sellId  = (int)$request->get('sell_id', 0);

        $sprSellMapper = SprSellMapper::getInstance();
        $model         = $sprSellMapper->fetch([
            'id'     => $sellId,
            'uid'    => $uid,
            'status' => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
        ]);

        if(!$model instanceof \SparringSellModel || empty($model->getId())) {
            return \Response::error('求大腿信息不能删除', 10226);
        }

        $model->setStatus(\Lib\Consts::SPARRING_SELL_STATUS_DEL);

        try {
            $rows = $sprSellMapper->update($model, [
                'id'  => $sellId,
                'uid' => $uid,
            ]);
            return $rows > 0 ? \Response::data(null) : \Response::error('我的发布中大腿信息删除失败', 10226);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

}
